//
//  ContentView.swift
//  ToDo4
//
//  Created by Jeyi Zhou on 2025/10/26.
//

import SwiftUI

struct ExportContent: Identifiable {
    let id = UUID()
    let content: String
}

struct ContentView: View {
    @StateObject private var todoManager = TodoManager()
    @State private var focusedQuadrant: (Quadrant, String, Color)? = nil
    @State private var exportData: ExportContent? = nil
    @State private var showingImport = false
    @State private var importText = ""
    @State private var importResult: ImportResult?
    @State private var isImporting = false
    
    var body: some View {
        Group {
            if let focusedQuadrant = focusedQuadrant {
                // 专注模式视图
                QuadrantFocusView(
                    quadrant: focusedQuadrant.0,
                    title: focusedQuadrant.1,
                    color: focusedQuadrant.2,
                    todos: getSortedTodos(for: focusedQuadrant.0),
                    onBack: {
                        self.focusedQuadrant = nil
                    },
                    onTodoToggle: { todo in
                        todoManager.toggleTodoCompletion(todo)
                    },
                    onTodoDelete: { todo in
                        todoManager.deleteTodo(todo)
                        todoManager.showFeedback("任务已删除")
                    },
                    onTodoEdit: { todo in
                        todoManager.startEditTodo(todo)
                    }
                )
                .sheet(isPresented: $todoManager.showAddTodo) {
                    AddTodoView(todoManager: todoManager)
                }
                .sheet(isPresented: $todoManager.showEditTodo) {
                    if let editingTodo = todoManager.editingTodo {
                        EditTodoView(todoManager: todoManager, todo: editingTodo)
                    }
                }
                .alert("提示", isPresented: $todoManager.showAlert) {
                    Button("确定") { }
                } message: {
                    Text(todoManager.alertMessage)
                }
            } else {
                // 四象限视图
                VStack(spacing: 0) {
                    // 标题栏
                    HStack {
                        // 导入按钮
                        Button(action: {
                            showingImport = true
                        }) {
                            Image(systemName: "square.and.arrow.down")
                                .font(.title2)
                                .foregroundColor(.gray)
                        }
                        .padding(.leading, 24)
                        .help("导入数据")

                        // 导出按钮
                        Button(action: {
                            if let exportedData = todoManager.exportAllTodos() {
                                exportData = ExportContent(content: exportedData)
                            } else {
                                todoManager.showFeedback("导出失败")
                            }
                        }) {
                            Image(systemName: "square.and.arrow.up")
                                .font(.title2)
                                .foregroundColor(.gray)
                        }
                        .help("导出数据")

                        Spacer()

                        Text("四象限 Todo")
                            .font(.largeTitle)
                            .fontWeight(.bold)

                        Spacer()

                        // 添加任务按钮
                        Button(action: {
                            todoManager.showAddTodo = true
                        }) {
                            Image(systemName: "plus.circle.fill")
                                .font(.title2)
                                .foregroundColor(.blue)
                        }
                        .padding(.trailing, 24)
                        .help("添加新任务")
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 24)
                    .padding(.bottom, 8)   // 进一步减少底部间距
                    .frame(maxWidth: .infinity)
                    
                    // 四象限网格
                    GeometryReader { geometry in
                        let quadrants = [
                            (Quadrant.urgentImportant, "紧急重要", Color.red),
                            (Quadrant.importantNotUrgent, "重要不紧急", Color.orange),
                            (Quadrant.urgentNotImportant, "紧急不重要", Color.yellow),
                            (Quadrant.notUrgentNotImportant, "不紧急不重要", Color.green)
                        ]

                        // 计算每个象限的动态高度
                        let quadrantHeight = calculateDynamicQuadrantHeight(geometry.size.height)

                        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 2), spacing: 24) {
                            ForEach(quadrants, id: \.0) { quadrant, title, color in
                                QuadrantView(
                                    quadrant: quadrant,
                                    title: title,
                                    color: color,
                                    todos: getSortedTodos(for: quadrant),
                                    height: quadrantHeight,
                                    onTodoToggle: { todo in
                                        todoManager.toggleTodoCompletion(todo)
                                    },
                                    onTodoDelete: { todo in
                                        todoManager.deleteTodo(todo)
                                        todoManager.showFeedback("任务已删除")
                                    },
                                    onTodoEdit: { todo in
                                        todoManager.startEditTodo(todo)
                                    },
                                    onTitleDoubleClick: {
                                        self.focusedQuadrant = (quadrant, title, color)
                                    }
                                )
                            }
                        }
                        .padding(.horizontal, 16)   // 减少左右padding
                        .padding(.bottom, 16)      // 减少底部padding
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .sheet(isPresented: $todoManager.showAddTodo) {
                    AddTodoView(todoManager: todoManager)
                }
                .sheet(isPresented: $todoManager.showEditTodo) {
                    if let editingTodo = todoManager.editingTodo {
                        EditTodoView(todoManager: todoManager, todo: editingTodo)
                    }
                }
                .alert("提示", isPresented: $todoManager.showAlert) {
                    Button("确定") { }
                } message: {
                    Text(todoManager.alertMessage)
                }
                .sheet(item: $exportData) { data in
                    VStack {
                        Text("导出数据")
                            .font(.title2)
                            .padding()

                        Text("请复制下面的JSON数据:")
                            .padding(.bottom, 8)

                        ScrollView {
                            TextEditor(text: .constant(data.content))
                                .frame(height: 300)
                                .padding()
                                .border(Color.gray, width: 1)
                        }

                        HStack {
                            Button("复制") {
                                let pasteboard = NSPasteboard.general
                                pasteboard.clearContents()
                                pasteboard.setString(data.content, forType: .string)
                                todoManager.showFeedback("数据已复制到剪贴板")
                            }
                            .padding(.trailing)

                            Button("关闭") {
                                exportData = nil
                            }
                            .padding(.leading)
                        }
                        .padding()
                    }
                    .frame(width: 600, height: 450)
                }
                .sheet(isPresented: $showingImport) {
                    VStack {
                        Text("导入数据")
                            .font(.title2)
                            .padding()

                        if isImporting {
                            VStack(spacing: 16) {
                                ProgressView()
                                    .scaleEffect(1.5)
                                Text("正在导入数据，请稍候...")
                                    .foregroundColor(.secondary)
                            }
                            .frame(height: 350)
                        } else {
                            Text("请粘贴导出的JSON数据:")
                                .padding(.bottom, 8)

                            ScrollView {
                                TextEditor(text: $importText)
                                    .frame(height: 300)
                                    .padding()
                                    .border(Color.gray, width: 1)
                                    .disabled(isImporting)
                            }
                        }

                        HStack {
                            Button("导入") {
                                performImport()
                            }
                            .disabled(isImporting || importText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                            .padding(.trailing)

                            Button("关闭") {
                                if !isImporting {
                                    showingImport = false
                                    importText = ""
                                    importResult = nil
                                }
                            }
                            .disabled(isImporting)
                            .padding(.leading)
                        }
                        .padding()
                    }
                    .frame(width: 600, height: 450)
                }
                .alert("导入结果", isPresented: .constant(importResult != nil)) {
                    Button("确定") {
                        importResult = nil
                    }
                } message: {
                    if let result = importResult {
                        VStack(alignment: .leading, spacing: 8) {
                            Text("成功导入: \(result.imported) 个任务")
                            Text("跳过重复: \(result.skipped) 个任务")

                            if !result.errors.isEmpty {
                                Text("错误信息:")
                                    .fontWeight(.bold)
                                ForEach(result.errors, id: \.self) { error in
                                    Text("• \(error)")
                                        .font(.caption)
                                        .foregroundColor(.red)
                                }
                            }
                        }
                    }
                }
            }
        }
        .frame(minWidth: 800, maxWidth: .infinity, minHeight: 600, maxHeight: .infinity)
    }
    
    private func getSortedTodos(for quadrant: Quadrant) -> [TodoItem] {
        let quadrantTodos = todoManager.todos.filter { $0.quadrant == quadrant }
        return quadrantTodos.sorted { todo1, todo2 in
            // 未完成的任务排在前面
            if !todo1.isCompleted && todo2.isCompleted {
                return true
            }
            // 已完成的任务排在后面
            if todo1.isCompleted && !todo2.isCompleted {
                return false
            }
            // 同为未完成或已完成的任务，按更新时间排序
            return todo1.updatedAt > todo2.updatedAt
        }
    }

    // 计算每个象限的动态高度
    private func calculateDynamicQuadrantHeight(_ totalHeight: CGFloat) -> CGFloat {
        let titleHeight: CGFloat = 64     // 标题栏实际高度 (24+8+32)
        let topPadding: CGFloat = 24      // 标题栏上边距
        let bottomPadding: CGFloat = 16   // 内容底部边距 (已减少)
        let spacing: CGFloat = 24         // 象限间距 (垂直方向一组)

        // 总的固定高度 = 标题栏 + 上边距 + 下边距 + 象限间距
        let fixedHeight = titleHeight + topPadding + bottomPadding + spacing
        let availableHeight = totalHeight - fixedHeight

        // 分成两行，每行高度
        let rowHeight = availableHeight / 2

        // 设置合理范围：最小200，最大600
        return max(200, min(600, rowHeight))
    }

  
    private func performImport() {
        guard !importText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            todoManager.showFeedback("请输入要导入的数据")
            return
        }

        // 设置导入状态为处理中
        isImporting = true

        // 使用异步操作模拟处理时间，让用户看到处理状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let result = todoManager.importTodos(from: importText)

            // 重置导入状态
            isImporting = false
            importResult = result

            // 如果成功导入任务，关闭导入窗口并清空文本
            if result.imported > 0 {
                showingImport = false
                importText = ""
            }
            // 不再需要showFeedback，因为详情弹窗会显示结果
        }
    }
}

#Preview {
    ContentView()
}
